package com.wanghlme.day26.dao.impl;

import com.wanghlme.day26.dao.IEmpDao;
import com.wanghlme.day26.pojo.Emp;
import com.wanghlme.day26.util.IRowWrapper;
import com.wanghlme.day26.util.JdbcTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class EmpDaoImpl implements IEmpDao {
    JdbcTemplate<Emp> template;

    public EmpDaoImpl() {
        template = new JdbcTemplate<>();
    }

    private class EmpWrapper implements IRowWrapper<Emp> {

        @Override
        public Emp transfer(ResultSet rs) throws SQLException {
            Emp emp = new Emp();
            emp.setEmpAge(rs.getInt("emp_age"));
            emp.setEmpId(rs.getInt("emp_id"));
            emp.setEmpLogin(rs.getString("emp_login"));
            emp.setEmpName(rs.getString("emp_name"));
            emp.setEmpPwd(rs.getString("emp_pwd"));
            emp.setEmpHiredate(rs.getTimestamp("emp_hiredate"));
            return emp;
        }
    }

    @Override
    public Emp queryEmpByLogin(String username, String password) {
        String sql = "select emp_id,emp_name,emp_login,emp_pwd,emp_hiredate,emp_age "
                + "from emp_old where emp_login=? and emp_pwd=?";
        return template.queryForOne(sql, new Object[]{username, password}, new EmpWrapper());
    }

    @Override
    public List<Emp> listAllEmployee() {
        String sql = "select emp_id, emp_name, emp_login, emp_pwd, emp_hiredate, emp_age from emp_old;";
        return template.queryForList(sql, null, new EmpWrapper());
    }

    @Override
    public int saveEmp(Emp emp) {
        if (emp.getEmpId() != null) {
            String sql = "update emp set emp_name=?,emp_login=?,emp_hiredate=?,emp_age=? where emp_id=?";
            return template.executeUpdate(sql, new Object[]{
                    emp.getEmpName(),
                    emp.getEmpLogin(),
                    emp.getEmpHiredate(),
                    emp.getEmpAge(),
                    emp.getEmpId()
            });
        } else {
            String sql = "insert into emp(emp_name,emp_login,emp_pwd,emp_hiredate,emp_age) values(?,?,?,?,?)";
            return template.executeUpdate(sql, new Object[]{
                    emp.getEmpName(),
                    emp.getEmpLogin(),
                    emp.getEmpPwd(),
                    emp.getEmpHiredate(),
                    emp.getEmpAge()
            });
        }

    }

    @Override
    public int delEmp(Integer id) {
        String sql = "delete from emp_old where emp_id=?";
        return template.executeUpdate(sql, new Object[]{id});
    }

    @Override
    public Emp queryOneById(Integer id) {
        String sql = "select emp_id,emp_name,emp_login,emp_pwd,emp_hiredate,emp_age from emp_old where emp_id=?";
        return template.queryForOne(sql, new Object[]{id}, new EmpWrapper());
    }
}
